package servlet.account.control;

import jakarta.servlet.annotation.WebServlet;
import mysql.JdbcUtil;

import jakarta.servlet.*;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.*;
@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final String SQL_FIND_PASSWORD = "SELECT password,level,ico_accounts FROM accounts WHERE username = ?";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 创建JdbcUtil的实例
        JdbcUtil ju = new JdbcUtil();
        try (Connection conn = ju.connectMySQL(); // 使用实例来调用非静态方法
             PreparedStatement pstmt = conn.prepareStatement(SQL_FIND_PASSWORD)) {

            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    String storedPassword = rs.getString("password");
                    String ico=rs.getString("ico_accounts");
                    String userlevel=rs.getString("level");
                    if (storedPassword.equals(password)) {
                        HttpSession session =req.getSession();
                        String sessionId = session.getId();
                        // 在服务器端存储Session ID和用户信息
                        session.setAttribute("username", username);
                        session.setAttribute("password", password);
                        session.setAttribute("ico", ico);
                        // 将Session ID作为Cookie发送给浏览器
                        Cookie sessionCookie = new Cookie("SESSIONID", sessionId);
                        sessionCookie.setMaxAge(-1); // 关闭浏览器时删除Cookie
                        resp.addCookie(sessionCookie);
                        // 密码正确，根据用户级别转发
                        sendRedirectToUserPage(req,resp,userlevel);
                    } else {
                        // 密码错误
                        req.setAttribute("loginError", "密码错误");
                        forwardToLoginPage(req, resp);
                    }
                } else {
                    // 账号不存在
                    req.setAttribute("loginError", "账号不存在");
                    ju.disconnectMySQL();
                    forwardToLoginPage(req, resp);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void sendRedirectToUserPage(HttpServletRequest req, HttpServletResponse resp, String uesrleve) throws ServletException, IOException {
        // 根据用户级别转发到相应的页面
        String userPage = "Home"; // 默认为普通用户页面
        // 假设有一个方法可以根据用户名获取用户级别
        if ("admin".equals(getUserLevel(uesrleve))) {
            userPage = "admin";
        }
        resp.sendRedirect(userPage);
    }

    private String getUserLevel(String userleve) {
        // 这里应该有一个查询数据库获取用户级别的逻辑
        // 为了示例，我们假设所有用户名包含"admin"的都是管理员
        return userleve.contains("admin") ? "admin" : "user";
    }

    private void forwardToLoginPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher dispatcher = req.getRequestDispatcher("/chushi/jsp/login.jsp");
        dispatcher.forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        forwardToLoginPage(req, resp);
    }
}
